package com.ymall.util;

import com.ymall.common.RedisShardedPool;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.ShardedJedis;

/**
 * Created by EvenLee on 2018/1/14.
 */
@Slf4j
public class JedisShardedUtil {

    public static String get(String key){
        ShardedJedis jedis = null;
        String result = null;
        try {
            jedis = RedisShardedPool.getJedis ();
            result = jedis.get (key);
        }catch (Exception e){
            log.error ("Jedis error : get key{} ",key,e);
            RedisShardedPool.returnBrokenResource (jedis);
            return result;
        }

        RedisShardedPool.returnResource (jedis);
        return result;
    }

    public static Long setnx(String key,String value){
        ShardedJedis jedis = null;
        Long result  = null;
        try {
           jedis = RedisShardedPool.getJedis ();
            result = jedis.setnx (key, value);
        }catch (Exception e){
            log.error ("Jedis error : setnx key{} value{}",key,value,e);
            RedisShardedPool.returnBrokenResource (jedis);
            return result;
        }
        RedisShardedPool.returnResource (jedis);
        return result;
    }

    public static Long expire(String key,int exTime){
        ShardedJedis jedis = null;
        Long result = null;
        try {
            jedis = RedisShardedPool.getJedis ();
            jedis.expire (key, exTime);
        }catch (Exception e){
            log.error ("Jedis error : expire key{} value{}",key,exTime,e);
            RedisShardedPool.returnBrokenResource (jedis);
            return result;
        }
        RedisShardedPool.returnResource (jedis);
        return result;
    }

    public static Long del(String key){
        ShardedJedis jedis = null;
        Long result = null;
        try {
            jedis = RedisShardedPool.getJedis ();
            result = jedis.del (key);
        }catch (Exception e){
            log.error ("Jedis error : del key{} value{}",key,e);
            RedisShardedPool.returnBrokenResource (jedis);
            return result;
        }
        RedisShardedPool.returnResource (jedis);
        return result;
    }
}
